package com.example.client_group5;

import java.io.ByteArrayOutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.util.Log;


import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;


import util.HttpClientFactory;

import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View.OnClickListener;
public class EditProfileActivity extends Activity {

	private final int CAMERA_PICTURE = 1;
    private final int GALLERY_PICTURE = 2;
    private Intent pictureActionIntent = null;
    private ImageView avatar;
    private Bitmap avatarBitmap;
    private static String encodeString;
    private EditText nameText;
    private EditText bioText;
    private EditText webText;
    private EditText locationText;
    private Button save;
    private Button cancel;
//    private UserManager userProfile;
    private ImageManager img;
    private ProgressBar progressBar;
    String[] infor;
    private UserManager userProfile;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//				WindowManager.LayoutParams.FLAG_FULLSCREEN);
//		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_edit_profile);
        Bundle b = getIntent().getExtras();
        infor = b.getStringArray("profile");
        this.avatar=(ImageView)findViewById(R.id.avatar);
        this.progressBar=(ProgressBar)findViewById(R.id.progress_bar);
       
        img = ImageManager.getInstance(getApplicationContext());
        userProfile = SignInActivity.userProfile;
        img.displayImage(userProfile.getAvatar("avatar", ""), this, avatar, progressBar);
        avatar.setTag(userProfile.getAvatar("avatar", ""));
        TextView editAvatar=(TextView)findViewById(R.id.profilePhoto);
        this.nameText=(EditText)findViewById(R.id.name);
        this.nameText.setText(userProfile.getFullName("fullname", ""));
        this.bioText=(EditText)findViewById(R.id.bio);
        this.bioText.setText(userProfile.getBio("bio", ""));
        this.webText=(EditText)findViewById(R.id.web);
        this.webText.setText(userProfile.getWeb("web", ""));
        this.locationText=(EditText)findViewById(R.id.location);
        this.locationText.setText(userProfile.getLocation("location", ""));
        save=(Button)findViewById(R.id.saveBt);
        cancel=(Button)findViewById(R.id.cancelBt);
        save.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String avatarLink = "";
				String name=nameText.getText().toString();
				String bio=bioText.getText().toString();
				String web=webText.getText().toString();
				String location=locationText.getText().toString();
				List<NameValuePair> list=new ArrayList<NameValuePair>(5);
				list.add(new BasicNameValuePair("fullname", name.trim()));
				list.add(new BasicNameValuePair("bio", bio.trim()));
				list.add(new BasicNameValuePair("web", web.trim()));
				list.add(new BasicNameValuePair("address", location.trim()));
				//Log.d("encode","encode:"+EditProfileActivity.encodeString);
				if(EditProfileActivity.encodeString!=null)
				{	
					list.add(new BasicNameValuePair("avatar",EditProfileActivity.encodeString));
					//Log.d("encode","img:"+encodeString);
				}
				try {
					HttpClient client = HttpClientFactory.getThreadSafeClient();
					String url=Setting.ipServer+"/api/user/edit-user-info";
					ResponseHandler<String> res=new BasicResponseHandler();  
					HttpPost httppost = new HttpPost(url);
					httppost.setEntity(new UrlEncodedFormEntity(list));
					String response=client.execute(httppost, res);
					
					JSONObject rep=new JSONObject(response);
					
					avatarLink = rep.getString("avatar");
						
					}catch(Exception e){
						Log.e("log_tag", "Error in http connection "+e.toString());

				}
				infor[1] = name;
				userProfile.saveFullName("fullname", name);
				userProfile.saveBio("bio", bio);
				userProfile.saveWeb("web", web);
				userProfile.saveLocation("location", location);
				userProfile.saveAvatar("avatar", avatarLink);
				
				Intent i = new Intent(EditProfileActivity.this, ProfileActivity.class);
				Bundle b = new Bundle();
				b.putStringArray("user", infor);
				i.putExtras(b);
				startActivity(i);
				finish();
			}
			
		});
        cancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				nameText.setText("");
//				bioText.setText("");
//				webText.setText("");
//				locationText.setText("");
				
				Intent i = new Intent(EditProfileActivity.this, ProfileActivity.class);
				Bundle b = new Bundle();
				
				b.putStringArray("user", infor);
				i.putExtras(b);
				startActivity(i);
				finish();
			}
		});
    

        editAvatar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				startDialog();
			}
		});
    }

    private void startDialog() {
        AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
        myAlertDialog.setTitle("Upload Pictures Option");
        myAlertDialog.setMessage("How do you want to set your picture?");

        myAlertDialog.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                pictureActionIntent = new Intent(Intent.ACTION_GET_CONTENT, null);
                pictureActionIntent.setType("image/*");
                pictureActionIntent.putExtra("return-data", true);
                startActivityForResult(pictureActionIntent, GALLERY_PICTURE);
            }
        });

        myAlertDialog.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                pictureActionIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(pictureActionIntent, CAMERA_PICTURE);
            }
        });
        myAlertDialog.show();
        

    }
    public Bitmap getBitmap(String bitmapUrl) {
		try {
			URL url = new URL(bitmapUrl);
		    return BitmapFactory.decodeStream(url.openConnection().getInputStream()); 
		}
		catch(Exception ex) {return null;}
	}

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GALLERY_PICTURE) {
            if(data != null){
        		 Uri selectedImage = data.getData();
	             String[] filePathColumn = {MediaStore.Images.Media.DATA};
	
	             Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
	             cursor.moveToFirst();
	
	             int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
	             String filePath = cursor.getString(columnIndex);
	             cursor.close();
	             
	             this.avatarBitmap = BitmapFactory.decodeFile(filePath);
	             
	             
	             avatar.setImageBitmap(avatarBitmap);
	             ByteArrayOutputStream encodeStream=new ByteArrayOutputStream();
	             avatarBitmap.compress(Bitmap.CompressFormat.JPEG,90, encodeStream);
	             byte [] encodeByte=encodeStream.toByteArray();
	             EditProfileActivity.encodeString=Base64.encodeBytes(encodeByte);
	            // Log.d("encode","img:"+encodeString);
	             cursor.close();
        	 }
        	 else{
        		 Toast toast = Toast.makeText(this, "No Image is selected.", Toast.LENGTH_LONG);
                 toast.show();
        	 }

        }
        else if (requestCode == CAMERA_PICTURE) {
            if (data!= null) {
                // here is the image from camera
            	this.avatarBitmap = (Bitmap) data.getExtras().get("data");
                avatar.setImageBitmap(avatarBitmap);
                ByteArrayOutputStream encodeStream=new ByteArrayOutputStream();
	             avatarBitmap.compress(Bitmap.CompressFormat.JPEG,90, encodeStream);
	             byte [] encodeByte=encodeStream.toByteArray();
	             EditProfileActivity.encodeString=Base64.encodeBytes(encodeByte);
            }
            else{
       		 Toast toast = Toast.makeText(this, "No Image is selected.", Toast.LENGTH_LONG);
                toast.show();
       	 }

        }
    }
    public boolean onKeyDown(int keyCode, KeyEvent event){
		if(keyCode == KeyEvent.KEYCODE_BACK){
			finish();
		}
		return false;
		
	}
    public void onDestroy(){
    	System.gc();
    	super.onDestroy();
    }
}
